package com.ziq.zcamp.post

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.View
import android.widget.Toast
import com.blankj.utilcode.util.SpanUtils
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter
import com.donkingliang.groupedadapter.holder.BaseViewHolder
import com.facebook.imagepipeline.request.ImageRequest
import com.ziq.base.extension.click
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.post.CommentDeleteParam
import com.ziq.zcamp.api.request.post.CommentLikeParam
import com.ziq.zcamp.bean.post.CommentItem
import com.ziq.zcamp.bean.post.ReplyCommentItem
import com.ziq.zcamp.databinding.ItemCommentBinding
import com.ziq.zcamp.databinding.ItemCommentReplyBinding
import com.ziq.zcamp.databinding.ItemCommentReplyMoreBinding
import com.ziq.zcamp.dialog.AlertDialog
import com.ziq.zcamp.dialog.CommentActionPopupWindow
import com.ziq.zcamp.life.CampLifeActivity
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ClipBoardUtil
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.TimeUtil

class AllCommentAdapter(val context: Context, val mViewModel: CommentViewModel, val source: String) : GroupedRecyclerViewAdapter(context, true) {

        interface ActionListener{
            fun onCommentUserInfoClick(item: CommentItem)
            fun onReplyCommentUserInfoClick(item: ReplyCommentItem)
            fun onCommentItemClick(item:CommentItem, groupPosition: Int, adapterPosition:Int)
            fun onReplyCommentItemClick(item:ReplyCommentItem, groupPosition: Int, adapterPosition:Int)
        }

        private var commentActionPopupWindow : CommentActionPopupWindow? = null
        private var mActionListener : ActionListener? = null

        private var dataList: List<CommentItem>? = arrayListOf()

        fun setData(list: List<CommentItem>?) {
            dataList = list
            notifyDataChanged()
        }

        fun setActionListener(listener: ActionListener){
            this.mActionListener = listener
        }

        override fun getGroupCount(): Int {
            return dataList?.size?:0
        }

        override fun getChildrenCount(groupPosition: Int): Int {
            return dataList?.get(groupPosition)?.reply_content?.size?:0
        }

        override fun hasHeader(groupPosition: Int): Boolean {
            return true
        }

        override fun hasFooter(groupPosition: Int): Boolean {
            return dataList?.get(groupPosition)?.has_more?:false
        }

        override fun getHeaderLayout(viewType: Int): Int {
            return R.layout.item_comment
        }

        override fun getChildLayout(viewType: Int): Int {
            return R.layout.item_comment_reply
        }

        override fun getFooterLayout(viewType: Int): Int {
            return R.layout.item_comment_reply_more
        }

        override fun onBindHeaderViewHolder(holder: BaseViewHolder?, groupPosition: Int) {
            holder?.let {
                val binding = holder.getBinding<ItemCommentBinding>()
                dataList?.get(groupPosition)?.let { it1 ->
                    CommentBindingViewHolder(binding, it).onBindViewHolder(
                        groupPosition,
                        it1
                    )
                }
            }
        }

        override fun onBindChildViewHolder(
            holder: BaseViewHolder?,
            groupPosition: Int,
            childPosition: Int
        ) {
            holder?.let {
                val binding = holder.getBinding<ItemCommentReplyBinding>()
                dataList?.get(groupPosition)?.reply_content?.get(childPosition)?.let { it1 ->
                    it1.parent = dataList?.get(groupPosition)
                    ReplyCommentBindingViewHolder(binding, it).onBindViewHolder(
                        groupPosition,
                        it1
                    )
                }
            }
        }

        override fun onBindFooterViewHolder(holder: BaseViewHolder?, groupPosition: Int) {
            holder?.let {
                val binding = holder.getBinding<ItemCommentReplyMoreBinding>()
                binding.more.click {
                    dataList?.get(groupPosition)?.let {
                        mViewModel.findMoreCommentReply(mViewModel.postId, it)
                    }
                }
            }
        }

        inner class CommentBindingViewHolder(val binding: ItemCommentBinding, val holder: BaseViewHolder) {

            @SuppressLint("SetTextI18n")
            fun onBindViewHolder(groupPosition: Int, item : CommentItem){
                binding.name.text = "${item.user_info?.nick_name}"
                binding.content.text = "${item.content}"
                binding.tvCampLifeBadge.setCampNum(item.user_info?.camping_count)
                binding.tvCampLifeBadge.click {
                    CampLifeActivity.open(it.context,item.user_info?.uid)
                }
                if(item.create_time != null){
                    binding.time.text = TimeUtil.getCommentTime(item.create_time!! * 1000)
                }

                if(item.user_info?.ip_locate?.isNotEmpty() == true){
                    binding.vIpDot.visibility = View.VISIBLE
                    binding.tvIp.visibility = View.VISIBLE
                    binding.tvIp.text = "${item.user_info?.ip_locate}"
                } else {
                    binding.vIpDot.visibility = View.GONE
                    binding.tvIp.visibility = View.GONE
                }

                ImageUtil.updateImageFromNetwork(binding.avator, "${item.user_info?.header_url}", ImageRequest.CacheChoice.DEFAULT)

                binding.name.click {
                    mActionListener?.onCommentUserInfoClick(item)
                }
                binding.avator.click {
                    mActionListener?.onCommentUserInfoClick(item)
                }

                updateLikeUI(item)

                binding.llPraise.click {
                    LoginActivity.checkLogin( object : ActionAfterLogin {
                        override fun action() {
                            val param = CommentLikeParam()
                            param.post_id = item.post_id
                            param.comment_id = item.comment_id
                            param.c_type = 1
                            if(item.like_status == 1){
                                onUnLike(item)
                                param.is_cancel = true
                                mViewModel.updateCommentLikeStatus(param, onFail = {
                                    onLike(item)
                                })
                            } else {
                                onLike(item)
                                param.is_cancel = false
                                mViewModel.updateCommentLikeStatus(param, onFail = {
                                    onUnLike(item)
                                })
                            }
                        }
                    })
                }


                holder.itemView.click {
                    LoginActivity.checkLogin( object : ActionAfterLogin {
                        override fun action() {
                            mActionListener?.onCommentItemClick(item, groupPosition, holder.adapterPosition)
                        }
                    })
                }

                if(item.user_info?.uid != null && item.user_info?.uid == mViewModel.create_uid){
                    binding.authorLabel.visibility = View.VISIBLE
                }else {
                    binding.authorLabel.visibility = View.GONE
                }

                holder.itemView.setOnLongClickListener {
                    val actionList = mutableListOf<String>(GlobalContextManager.getString(R.string.copy))
                    if(item.user_info?.uid == UserManager.instance.getUid()){
                        actionList.add(GlobalContextManager.getString(R.string.delete))
                    }
                    commentActionPopupWindow?.dismiss()
                    commentActionPopupWindow = CommentActionPopupWindow(holder.itemView.context, actionList)
                    commentActionPopupWindow?.isOutsideTouchable = true
                    commentActionPopupWindow?.setActionCallback {
                        when(it){
                            GlobalContextManager.getString(R.string.copy) -> {
                                ClipBoardUtil.addToClipboard(GlobalContextManager.appContext, item.content?:"")
                                val msg = GlobalContextManager.getString(R.string.copy_success)
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                            }
                            GlobalContextManager.getString(R.string.delete) -> {
                                onDeleteComment(item)
                            }
                        }
                    }
                    commentActionPopupWindow!!.contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
                    val popupWidth: Int = commentActionPopupWindow!!.contentView.getMeasuredWidth()
                    val popupHeight: Int = commentActionPopupWindow!!.contentView.getMeasuredHeight()
                    val location = IntArray(2)
                    holder.itemView.getLocationOnScreen(location)
                    commentActionPopupWindow?.showAsDropDown(holder.itemView,
                        holder.itemView.getWidth() / 2 - popupWidth / 2,
                        -(holder.itemView.height + popupHeight))
                    return@setOnLongClickListener true
                }
            }

            fun onLike(item:CommentItem){
                item.like_status = 1
                val likeNum = item.like_num?:0
                item.like_num = likeNum + 1
                updateLikeUI(item)
            }

            fun onUnLike(item:CommentItem){
                item.like_status = 0
                val likeNum = item.like_num?:0
                if(likeNum > 0 ){
                    item.like_num = likeNum - 1
                }
                updateLikeUI(item)
            }

            fun updateLikeUI(item:CommentItem){
                binding.llPraise.isSelected = item.like_status == 1
                binding.tvPraiseCount.text = if(item.like_num?:0 > 0) "${item.like_num}" else ""
            }

            fun onDeleteComment(item:CommentItem){
                AlertDialog(context)
                    .setTitle {
                        it.append(GlobalContextManager.getString(R.string.are_you_sure_delete_comment))
                    }
                    .setCancelButton(text = {it.append(GlobalContextManager.getString(R.string.cancel))}, action = {it.dismiss()})
                    .setConfirmButton(text = {it.append(GlobalContextManager.getString(R.string.confirm))}, action = {
                        it.dismiss()
                        val param = CommentDeleteParam()
                        param.post_id = mViewModel.postId
                        param.comment_id = item.comment_id
                        param.c_type = 1
                        mViewModel.deleteComment(param, onSuccess = {
                            if(mViewModel.commentData.value?.contains(item) == true){
                                mViewModel.commentData.value?.remove(item)
                                mViewModel.commentData.postValue(mViewModel.commentData.value)
                                if(mViewModel.commentCount.value?:0 > 0){
                                    mViewModel.commentCount.postValue((mViewModel.commentCount.value?:0) - 1)
                                }
                            }
                        })
                    })
                    .show()
            }

        }

        inner class ReplyCommentBindingViewHolder(val binding: ItemCommentReplyBinding, val holder: BaseViewHolder) {

            @SuppressLint("SetTextI18n")
            fun onBindViewHolder(groupPosition: Int, item : ReplyCommentItem){
                binding.name.text = "${item.reply_info?.nick_name}"
                binding.tvCampLifeBadge.setCampNum(item.reply_info?.camping_count)
                binding.tvCampLifeBadge.click {
                    CampLifeActivity.open(it.context,item.reply_info?.uid)
                }

                if(item.be_replied_info != null && item.reply_type == 3){
                    val spanString = SpanUtils()
                        .append("回复 ").setForegroundColor(Color.parseColor("#333333"))
                        .append("${item.be_replied_info?.nick_name}: ").setForegroundColor(Color.parseColor("#999999"))
                        .append("${item.reply_msg}").setForegroundColor(Color.parseColor("#333333"))

                    binding.content.text = spanString.create()
                }else {
                    binding.content.text = "${item.reply_msg}"
                }

                if(item.reply_create_time != null){
                    binding.time.text = TimeUtil.getCommentTime(item.reply_create_time!! * 1000)
                }

                if(item.reply_info?.ip_locate?.isNotEmpty() == true){
                    binding.vIpDot.visibility = View.VISIBLE
                    binding.tvIp.visibility = View.VISIBLE
                    binding.tvIp.text = "${item.reply_info?.ip_locate}"
                } else {
                    binding.vIpDot.visibility = View.GONE
                    binding.tvIp.visibility = View.GONE
                }

                ImageUtil.updateImageFromNetwork(binding.avator, "${item.reply_info?.header_url}", ImageRequest.CacheChoice.DEFAULT)

                binding.name.click {
                    mActionListener?.onReplyCommentUserInfoClick(item)
                }
                binding.avator.click {
                    mActionListener?.onReplyCommentUserInfoClick(item)
                }

                updateLikeUI(item)

                binding.llPraise.click {
                    LoginActivity.checkLogin( object : ActionAfterLogin {
                        override fun action() {
                            val param = CommentLikeParam()
                            param.post_id = mViewModel.postId
                            param.comment_id = item.parent?.comment_id
                            param.reply_comment_id = item.reply_comment_id
                            param.c_type = item.reply_type
                            if(item.reply_like_status == 1){
                                onUnLike(item)
                                param.is_cancel = true
                                mViewModel.updateCommentLikeStatus(param, onFail = {
                                    onLike(item)
                                })
                            } else {
                                onLike(item)
                                param.is_cancel = false
                                mViewModel.updateCommentLikeStatus(param, onFail = {
                                    onUnLike(item)
                                })
                            }
                        }
                    })
                }


                holder.itemView.click {
                    LoginActivity.checkLogin( object : ActionAfterLogin {
                        override fun action() {
                            mActionListener?.onReplyCommentItemClick(item, groupPosition, holder.adapterPosition)
                        }
                    })
                }

                if(item.reply_info?.uid != null && item.reply_info?.uid == mViewModel.create_uid){
                    binding.authorLabel.visibility = View.VISIBLE
                }else {
                    binding.authorLabel.visibility = View.GONE
                }

                holder.itemView.setOnLongClickListener {
                    val actionList = mutableListOf<String>(GlobalContextManager.getString(R.string.copy))
                    if(item.reply_info?.uid == UserManager.instance.getUid()){
                        actionList.add(GlobalContextManager.getString(R.string.delete))
                    }
                    commentActionPopupWindow?.dismiss()
                    commentActionPopupWindow = CommentActionPopupWindow(holder.itemView.context, actionList)
                    commentActionPopupWindow?.isOutsideTouchable = true
                    commentActionPopupWindow?.setActionCallback {
                        when(it){
                            GlobalContextManager.getString(R.string.copy) -> {
                                ClipBoardUtil.addToClipboard(GlobalContextManager.appContext, item.reply_msg?:"")
                                val msg = GlobalContextManager.getString(R.string.copy_success)
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                            }
                            GlobalContextManager.getString(R.string.delete) -> {
                                onDeleteComment(item)
                            }
                        }
                    }
                    commentActionPopupWindow!!.contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
                    val popupWidth: Int = commentActionPopupWindow!!.contentView.getMeasuredWidth()
                    val popupHeight: Int = commentActionPopupWindow!!.contentView.getMeasuredHeight()
                    val location = IntArray(2)
                    holder.itemView.getLocationOnScreen(location)
                    commentActionPopupWindow?.showAsDropDown(holder.itemView,
                        holder.itemView.getWidth() / 2 - popupWidth / 2,
                        -(holder.itemView.height + popupHeight))
                    return@setOnLongClickListener true
                }
            }

            fun onLike(item:ReplyCommentItem){
                item.reply_like_status = 1
                val likeNum = item.reply_like_num?:0
                item.reply_like_num = likeNum + 1
                updateLikeUI(item)
            }

            fun onUnLike(item:ReplyCommentItem){
                item.reply_like_status = 0
                val likeNum = item.reply_like_num?:0
                if(likeNum > 0 ){
                    item.reply_like_num = likeNum - 1
                }
                updateLikeUI(item)
            }

            fun updateLikeUI(item:ReplyCommentItem){
                binding.llPraise.isSelected = item.reply_like_status == 1
                binding.tvPraiseCount.text = if(item.reply_like_num?:0 > 0) "${item.reply_like_num}" else ""
            }

            fun onDeleteComment(item:ReplyCommentItem){
                AlertDialog(context)
                    .setTitle {
                        it.append(GlobalContextManager.getString(R.string.are_you_sure_delete_comment))
                    }
                    .setCancelButton(text = {it.append(GlobalContextManager.getString(R.string.cancel))}, action = {it.dismiss()})
                    .setConfirmButton(text = {it.append(GlobalContextManager.getString(R.string.confirm))}, action = {
                        it.dismiss()
                        val param = CommentDeleteParam()
                        param.post_id = mViewModel.postId
                        param.comment_id = item.parent?.comment_id
                        param.reply_comment_id = item.reply_comment_id?:""
                        param.c_type = item.reply_type
                        mViewModel.deleteComment(param, onSuccess = {
                            item.parent?.reply_content?.remove(item)
                            mViewModel.commentData.postValue(mViewModel.commentData.value)
                        })
                    })
                    .show()
            }

        }


    }